package com.javaweb.service.Impl;


import com.javaweb.common.BusinessConstants;
import com.javaweb.common.ResponseResult;
import com.javaweb.dao.ArticleDao;
import com.javaweb.dao.CategoryDao;
import com.javaweb.dao.UserDao;
import com.javaweb.model.Article;
import com.javaweb.model.Category;
import com.javaweb.model.Tag;
import com.javaweb.model.User;
import com.javaweb.service.ArticleService;
import com.javaweb.service.dto.ArticleConditionDto;
import com.javaweb.service.dto.ArticleDto;
import com.javaweb.service.dto.ArticleUpdateDto;
import com.javaweb.service.dto.PageResult;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @desc:
 * @author: Ping
 * @date: 2024/10/16 9:47
 */

@Service
@Slf4j
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private UserDao userDao ;
    @Autowired
    private ArticleDao articleDao ;
    @Autowired
    private CategoryDao categoryDao;


    @Override
    public PageResult queryByArticleCondition(ArticleConditionDto articleCond, Integer pageNum, Integer pageSize) {
        // 检查输入参数
        if (pageNum == null || pageSize == null || pageNum < 1 || pageSize < 1) {
            throw new IllegalArgumentException("Invalid page number or page size");
        }

        // 获取符合条件的文章总数
        int total = articleDao.countByConditions(articleCond);

        // 计算分页起始位置
        int fromIndex = (pageNum - 1) * pageSize;
        List<Article> articles = articleDao.selectByConditions(articleCond, fromIndex, pageSize);

        // 创建 PageResult 对象并返回
        PageResult<Article> pageResult = new PageResult<>();
        pageResult.setData(articles);
        pageResult.setPageNum(pageNum);
        pageResult.setPageSize(pageSize);
        pageResult.setTotal(total);

        return pageResult;
    }

    @Transactional
    @Override
    public int publishArticle(String articelId, String userId) {
        // 更新文章状态，将其从默认的0改为1（表示发布）
        Integer updateStatusResult = articleDao.updateStatus(Integer.valueOf(articelId), BusinessConstants.ARTICLE_PUBLISHED);

        // 检查文章状态更新是否成功
        if (updateStatusResult <= 0) {
            log.error("文章状态更新失败" + articelId);
            return 0; // 返回0表示发布失败
        }

        // 更新用户积分
        Integer updateScoreResult = userDao.updateScore(Integer.valueOf(userId), BusinessConstants.ARTICLE_SCORE);

        // 检查用户积分更新是否成功
        if (updateScoreResult <= 0) {
            log.error("用户积分更新失败 " + userId);
            throw new RuntimeException("用户积分更新失败"); // 抛出异常以回滚事务
        }

        log.info("文章发布更新成功" + articelId);
        return 1; // 返回1表示发布成功
    }

    @Override
    public Article queryById(String articleId) {
        // 检查输入参数
        if (articleId == null || articleId.isEmpty()) {
            throw new IllegalArgumentException("articleId not is null or empty");
        }

        // 调用 DAO 层的方法获取文章
        Article article = articleDao.selectById(articleId);

        // 检查是否找到文章
        if (article == null) {
            log.warn("Article not found for articleId: " + articleId);
        }

        return article; // 返回查询结果
    }

    @Override
    public Article insertArticle(Article article) {
        articleDao.insert(article);
        return article;//返回带有新增id的article。
    }

    @Transactional
    @Override
    public int publishArticlesByBatch(String[] articleIds, String userId) {
        // 检查输入
        if (articleIds == null || articleIds.length == 0 || userId == null) {
            return 0; // 如果参数无效，直接返回0
        }
        int successfulUpdates = 0; // 记录成功发布的文章数量
        for (String articleId : articleIds) {
            // 更新文章状态
            Integer ret = articleDao.updateStatus(Integer.valueOf(articleId), BusinessConstants.ARTICLE_PUBLISHED);
            if (ret > 0) {
                // 如果状态更新成功，更新用户积分
                ret = userDao.updateScore(Integer.valueOf(userId), BusinessConstants.ARTICLE_SCORE);
                if (ret > 0) {
                    successfulUpdates++; // 计数成功发布的文章
                } else {
                    log.error("用户积分更新失败" + articleId);
                    throw new RuntimeException("用户积分更新失败"); // 如果积分更新失败，抛出异常
                }
            } else {
                log.error("文章状态更新失败 " + articleId);
                throw new RuntimeException("文章状态更新失败"); // 如果状态更新失败，抛出异常
            }
        }
        // 如果所有文章都成功发布，则返回1
        return successfulUpdates == articleIds.length ? 1 : 0;
    }

    @Transactional
    @Override
    public int updateArticle(ArticleUpdateDto articledto) {
        // 检查 ArticleUpdateDto 是否有效
        if (articledto.getId() == null || articledto.getTitle() == null) {
            return 0; // 表示失败
        }

        // 将 ArticleUpdateDto 转换为 Article 对象
        Article article = new Article();
        article.setId(Integer.valueOf(articledto.getId()));
        article.setTitle(articledto.getTitle());
        article.setContent(articledto.getContent());
        article.setDescription(articledto.getDescription());
        article.setCategoryId(Integer.valueOf(articledto.getCategoryId()));
        article.setStatus(Integer.valueOf(articledto.getStatus()));

        // 调用 ArticleDao 的更新方法
        return articleDao.updatearticle(article);
    }

    @Transactional
    @Override
    public int removeArticle(String articleId, String userId) {
        //删除文章
        int deletearticleret=articleDao.deleteById(Integer.parseInt(articleId));
        if (deletearticleret<0){
            log.error("文章删除失败" + articleId);
            return 0; // 返回0表示发布失败
        }
        // 更新用户积分
        Integer updateScoreResult = userDao.updateScore(Integer.valueOf(userId), BusinessConstants.DELETE_ARTICLE_SCORE);
        // 检查用户积分更新是否成功
        if (updateScoreResult <= 0) {
            log.error("用户积分更新失败 " + userId);
            throw new RuntimeException("用户积分更新失败"); // 抛出异常以回滚事务
        }
        log.info("文章删除成功" + articleId);
        return 1; // 返回1表示发布成功
    }

    @Override
    public List<Article> listArticles(ArticleConditionDto articleCond) {
        return articleDao.findArticlesByConditions(articleCond);
    }

    @Override
    public void add(ArticleDto articleDto) {
        Article article = new Article();
        article.setTitle(articleDto.getTitle());
        article.setContent(articleDto.getContent());
        article.setStatus(Integer.parseInt(articleDto.getStatus())); // 假设状态为整数

        //通过作者名来获取user_id
        User user= userDao.getUserByname(articleDto.getAuthorName());
        article.setUserId(user.getUserId()); // 获取当前用户的ID

        // 根据类别名称获取ID
        Category category=categoryDao.getCategoryByname(articleDto.getCategoryName());
        article.setCategoryId(category.getId()); // 根据类别名称获取ID

        // 处理标签并设置
        article.setTags(parseTags(articleDto.getTags()));

        // 设置创建和更新时间
        article.setCreateTime(new Date());
        article.setUpdateTime(new Date());

        // 调用 DAO 保存文章
        articleDao.add(article);
    }

    @Override
    public ResponseResult update(ArticleUpdateDto articleUpdateDto) {
        // 解析 tagIds 并将其转换为标签列表
        List<Integer> tagIds = parseTagIds(articleUpdateDto.getTagIds());

        // 调用 DAO 层进行更新
        boolean isUpdated = articleDao.updateArticle(articleUpdateDto, tagIds);

        if (isUpdated) {
            return  ResponseResult.ok(200, "文章更新成功");
        } else {
            return ResponseResult.error(HttpStatus.BAD_REQUEST, "文章更新失败");
        }
    }

    @Override
    public ResponseResult publish(String articleId) {
        boolean isPublished = articleDao.publishArticle(articleId);

        if (isPublished) {
            return  ResponseResult.ok(200, "文章发布成功");
        } else {
            return  ResponseResult.error(HttpStatus.BAD_REQUEST, "文章发布失败，未找到该文章");
        }
    }

    @Override
    public List<Article> findArticles(ArticleConditionDto articleCond) {
        return List.of();
    }

    @Override
    public void addArticle(ArticleDto articleDto) {
        articleDao.save(articleDto);

    }

    @Override
    public void publishArticle(String articleId) {
        articleDao.publish(articleId);
    }

    private List<Integer> parseTagIds(String tagIds) {
        List<Integer> tagIdList = new ArrayList<>();
        if (tagIds != null && !tagIds.isEmpty()) {
            String[] tagIdArray = tagIds.split(",");
            for (String tagId : tagIdArray) {
                tagIdList.add(Integer.parseInt(tagId.trim()));
            }
        }
        return tagIdList;
    }

    private List<Tag> parseTags(String tags) {
        List<Tag> tagList = new ArrayList<>();
        if (tags != null && !tags.isEmpty()) {
            String[] tagArray = tags.split(","); // 按逗号分隔字符串
            for (String tagName : tagArray) {
                Tag tag = new Tag();
                tag.setName(tagName.trim()); // 去除多余空格
                tagList.add(tag); // 添加到标签列表
            }
        }
        return tagList; // 返回标签列表
    }
}
